package com.jxy.bean.constant;

import com.jxy.bean.ClassFile;
import com.jxy.tool.Tool;

import java.io.DataInputStream;

public class NameAndTypeInfo extends ConstantPool {
    public int name_index;
    public int descriptor_index;

    public NameAndTypeInfo(DataInputStream dis, ClassFile cf) {
        super(ConstantPoolTag.CONSTANT_NameAndType.getTag(), cf);
        //长度u2
        name_index = Tool.readU2(dis);
        descriptor_index = Tool.readU2(dis);
    }

    public String getName() {
        if (valid()) {
            Utf8Info utf8Info = (Utf8Info) cf.getPools()[name_index];
            return utf8Info.getString();
        }
        return "name_index err !";
    }

    public String getDescriptor() {
        if (valid()) {
            Utf8Info utf8Info = (Utf8Info) cf.getPools()[descriptor_index];
            return utf8Info.getString();
        }
        return "descriptor_index err !";
    }

    @Override
    public String toString() {
        return ConstantPoolTag.CONSTANT_NameAndType.getType() + "{tag:" + tag + ", name_index:" + name_index + "(" + getName() + "), descriptor_index:" + descriptor_index + "(" + getDescriptor() + ")}";
    }

    @Override
    public boolean valid() {
        //name_index必须指向CONSTANT_Utf8_info结构
        if (cf.getPools()[name_index].getTag() == ConstantPoolTag.CONSTANT_Utf8.getTag()) {
            //descriptor_index必须指向CONSTANT_Utf8结构
            if (cf.getPools()[descriptor_index].getTag() == ConstantPoolTag.CONSTANT_Utf8.getTag()) {
                return true;
            }
        }
        return false;
    }
}
